/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */
define(['adminapp', 'jquery.timer', 'jquery-slimscroll', 'bootstrap-modal', 'bootstrap-modalmanager'], function ($app) {

    $app.navactive('member');

    var action_tpl = Handlebars.compile($(g.actiontpl).html());
    var status_tpl = Handlebars.compile($(g.statustpl).html());

    var doms = {
        'list'                  : 'member-list',
        'status_modal'          : 'import_status_modal',
        'import_member_btn'     : 'import_file_upload',
        'import_integral_upload': 'import_integral_upload',
        'ok_import_btn'         : 'ok_import_btn',
        'import_status'         : 'load_status'
    };

    var urls = {
        'list'         : g.ctx + "admin/member/list",
        'upload'       : g.ctx + 'admin/member/leadin',
        'import_status': g.ctx + 'admin/member/import_status',
        'start_import' : g.ctx + 'admin/member/start_import'
    };

    var $member_table = $app.listtable({
        'sAjaxSource' : urls.list,
        'aoColumns'   : [
            $app.checkall,
            $app.autono,
            {'mDataProp': 'id' },
            {'mDataProp': 'name' },
            {'mDataProp': 'id_card' },
            {'mDataProp': 'gender' },
            {'mDataProp': 'card_no' },
            {'mDataProp': 'birth' },
            {'mDataProp': 'phone' },
            {'mDataProp': 'rank' },
            {'mDataProp': 'wx_no' },
            {'mDataProp': 'currency' },
            {'mDataProp': 'integral' },
            {'mDataProp': 'status' },
            {'mDataProp': 'active' }
        ],
        'aoColumnDefs': [
            { 'bSearchable': false, 'bVisible': false, 'aTargets': [ 2, 13, 14 ] },
            {
                'aTargets': [5],
                'mData'   : null,
                'mRender' : function (data, type, full) {
                    var gender = full['gender'];
                    if (gender == 0) {
                        return '<span class="label label-default">女</span>';
                    } else if (gender == 1) {
                        return '<span class="label label-primary">男</span>';
                    } else {
                        return '<span class="label label-success">未知</span>';
                    }
                }
            },
            {
                'aTargets': [15],
                'mData'   : null,
                'mRender' : function (data, type, full) {
                    return action_tpl(full);
                }
            }
        ]
    }, doms.list);

    var $modal = $('#' + doms.status_modal);
    $app.uploader({
        'uploader'        : urls.upload,
        'buttonText'      : '导入会员基础信息',
        'width'           : 120,
        'height'          : 25,
        'fileTypeExts'    : '*.tsv',
        'fileTypeDesc'    : 'tsv数据文件',
        'hideButton'      : true,
        'successTimeout'  : 300,
        'onUploadComplete': function () {
            App.unblockUI();
        },
        //选择上传文件后调用
        'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            App.blockUI({message: '正在上传文件...'});
        },
        'onUploadSuccess' : function (file, data, response) {
            if (response) {
                var jsonData = eval('(' + data + ')');
                if (jsonData['status'] == 'OK') {
                    import_member.begin();
                } else {
                    bootbox.alert(jsonData['message']);
                }
            } else {
                bootbox.alert('服务器通信出现问题')
            }
        }
    }, doms.import_member_btn);

    $app.uploader({
        'uploader'        : urls.upload,
        'buttonText'      : '会员积分信息',
        'width'           : 100,
        'height'          : 25,
        'fileTypeExts'    : '*.xls;*.xlsx;',
        'fileTypeDesc'    : 'Excel文件',
        'hideButton'      : true,
        'successTimeout'  : 300,
        'onUploadComplete': function () {
            App.unblockUI();
        },
        //选择上传文件后调用
        'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            App.blockUI({message: '正在上传文件...'});
        },
        'onUploadSuccess' : function (file, data, response) {
            if (response) {
                var jsonData = eval('(' + data + ')');
                if (jsonData['status'] == 'OK') {
                    import_member.begin();
                } else {
                    bootbox.alert(jsonData['message']);
                }
            } else {
                bootbox.alert('服务器通信出现问题')
            }
        }
    }, doms.import_integral_upload);

    var $load_status = $('#' + doms.import_status);

    var $timer = $.timer(function () {
        $.get(urls.import_status, function (rst) {

            if (rst.status == 'NODATA') {
                // NODATA 这里用它来表示正在处理中!
                $load_status.append(status_tpl({line_data: rst.data}));
                $('#load_scroller').slimScroll({ scrollTo: $load_status.css('height') })
            } else {
                var $okBtn = $('#' + doms.ok_import_btn);
                $okBtn.removeAttr('disabled');
                $okBtn.addClass(' btn-primary');
                $okBtn.text('导入成功');
                $timer.stop();
                $member_table.fnReloadAjax();
            }
        })
    });
    $modal.on('hidden.bs.modal', function (e) {
        $load_status.empty();
    });
    var import_member = {
        begin: function () {
            $modal.modal();
            var $okBtn = $('#' + doms.ok_import_btn);
            $okBtn.attr('disabled', 'disabled');
            $okBtn.text('导入中...');
            $.get(urls.start_import, function (rst) {
                if (rst.status == 'OK') {
                    if ($timer.isActive) {
                        return;
                    }
                    $timer.set({time: 3000, autostart: true})
                } else {
                    alert.alert(rst.message);
                }
            })
        },
        end  : function () {
            $timer.stop();
        }
    };

    return {};
});